<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <h1 class="text-2xl text-center font-bold mt-6 mb-6">注册</h1>
      <van-field
        v-model="loginForm.username"
        name="username"
        label="用户名"
        left-icon="user"
        placeholder="请输入用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="loginForm.phone"
        name="phone"
        label="手机号"
        left-icon="phone"
        placeholder="请输入手机号"
        :rules="[{ required: true, message: '请填写手机号' }]"
      />
      <van-field
        v-model="loginForm.password"
        type="password"
        name="password"
        label="密码"
        placeholder="需要设置的密码"
        left-icon="lock"
        :rules="[
          { required: true, message: '请填写密码' },
          { validator: validatorVerifyPassword },
        ]"
      />
      <van-field
        v-model="loginForm.password2"
        type="password"
        name="password2"
        label="密码确认"
        placeholder="请再次输入密码"
        left-icon="lock"
        :rules="[{ required: true, message: '请再次输入密码' }]"
      />
      <div class="text-right leading-[3rem] mr-3">
        已有账号？<a class="text-blue-700 underline" href="/login">前往登录</a>
      </div>
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit">
        注册
      </van-button>
    </div>
  </van-form>
</template>

<script setup>
import { useRouter } from "vue-router";
import { useUserStore } from "@/store/modules/user";
import { reactive } from "vue";
import { showNotify } from "vant";

const userStore = useUserStore();
const router = useRouter();

const loginForm = reactive({
  phone: "",
  username: "",
  password: "",
  password2: "",
});

const validatorVerifyPassword = (val) => {
  // 验证是否超过6位数
  if (val.trim().length < 6) {
    return "请设置6位及以上密码！";
  }
};

const onSubmit = async (values) => {
  // 验证密码是否一致
  if (values.password !== values.password2) {
    return showNotify({ type: "danger", message: "输入密码不一致！" });
  }

  await userStore.register(loginForm);
  router.replace("/");
};
</script>
